var socketIo = require('socket.io');
var _ = require('lodash')
var read = require('hy5b/backend/read')
var path = require('path')

var TMP_PATH = path.resolve(__dirname, '../../../../tmp');

/**
 * 把原本深圳的数据挪到杭州，并匹配到随便选的一个数据配置的字段上
 * @param  {[type]} data [description]
 * @return {[type]}      [description]
 */
function change2HZ(data) {
  var newData = _.cloneDeep(data)
  _.map(data.collection, function(item, index) {
    newData.collection[index].classCode = String(parseFloat(item.longitude) + 6.0209)
    newData.collection[index].count = String(parseFloat(item.latitude) + 7.6657)
    newData.collection[index].ComputerRoom = item['object.alert']
    newData.collection[index].className = item['ip']
  })
  return newData
}

var topoData = {} //require('./data/topo-1')

function ioCreator(server, urlPath) {
  var io = socketIo(server, {
    path: urlPath
  });
  
  io.on('connection', function(socket) {
    console.log('socket connected');
    socket.on('add', function(dataSetId, sequenceId, filter, type) {      
      // setInterval(() => {
        const tpmTextPath = path.resolve(TMP_PATH, '2020/0331/ws.txt');
        read.eachLine(tpmTextPath, function(line) {
          if (line) {
            var params = parseWsString(line)
            var obj = params[1];
            // var obj = {}
            if (dataSetId === 'bdb24f053f864cca9300d4b1c608271c') { //MOCK统一可用，勿删
              obj.collection = require('../../api/data/_mock/data').data.collection;
              obj.collection = [obj.collection[obj.collection.length - 1]]
            } else if (dataSetId === 'e8fb30c5f9c8424da7fe0bf84b9a4b35') {
              console.log('[socketio: 发送模具]')
              obj.collection = topoData.molds
              _.each(obj.collection, (item) => {
                item['产品类别'] = item.code;
                item['产品名称'] = item.nodeId
                item['单位数量'] = item.name
              })
            } else if (dataSetId === '26f3e91d63c549c7b83e95b9c0cfc6bd') {
              console.log('[socketio: 发送连线]')
              obj.collection = topoData.links
              _.each(obj.collection, (item) => {
                item['仓库'] = item.source;
                item['产品'] = item.target;
                item['规格'] = item.name
              })
            } else if (dataSetId === 'storeset000000000000000000000002') {

            }

            obj.id = dataSetId;
            obj.sequence = sequenceId;
            obj.status = true
            
            // console.log(obj)
            console.log('[socketio: emit]', dataSetId, sequenceId)
            socket.emit('receive', encodeURIComponent(JSON.stringify(obj)));
          }
        })
      // }, 15 * 1000)
      
    })

    socket.on('disconnect', function() { //前端断开会使服务端收到一个disconnect事件
      console.log('[socketio: receive disconnect]');
    })

    socket.on('disconnection', function() {
      console.log('[socketio: receive disconnection]');
      //如果后端没有执行disconnect，当后端停止服务时，前端会尝试重连，当后端再次开启，前端会重连成功并产生一条新的连接
      // socket.disconnect() //调用会使服务端和客户端都收到一个disconnect事件
      // socket.leave() //没有事件
      // socket.emit('disconnect') //发送disconnect，客户端不会收到事件，但是自己却会收到一个disconnect事件
    })
  });
}

module.exports = ioCreator;

function parseWsString(wsReqContent) {
  var reg = /^[^\[]*(\[.*\])[\r\n]*$/;
  if (reg.test(wsReqContent)) {
    var paramString = wsReqContent.match(reg)[1];
    var paramArr = eval(paramString);
    var params = []
    for (var i = 0; i < paramArr.length; i++) {
      try {
        var param = decodeURIComponent(paramArr[i]);
        var obj = JSON.parse(param);
        params[i] = obj;
      } catch (e) {
        params[i] = paramArr[i]
      }
    }
    return params //['receive', obj, ...]
  }
  return null;
}